#!/bin/sh

# if app not exist
if [ ! -f /bin/miniupnpd ]; then
    exit 0
fi

# wait to start web and run from goahead code
. /etc/scripts/web_wait.sh
web_wait

# get params
. /etc/scripts/global.sh

if [ "$OperationMode" = "0" ] || [ "$ApCliBridgeOnly" = "1" ]; then
    exit 0
fi

LOG="logger -t upnpd"

start() {
 get_param
    if [ "$upnpEnabled" = "1" -a "$real_wan_ipaddr" != "" ] && [ "$OperationMode" != "0" -o "$vpnEnabled" = "on" ]; then
	$LOG "Start upnp at $real_wan_ipaddr"
	if [ ! -f /var/upnp_leases ]; then
	    touch /var/upnp_leases
	fi
	gen_config
	ip route replace $upmpm_net dev $lan_if
        miniupnpd -f /etc/miniupnpd.conf -i "$real_wan_if" -o "$real_wan_ipaddr" -a "$lan_ipaddr/$lan_netmask" &
    fi
}

gen_config() {
####################generate config###########################
printf "
minissdpdsocket=/var/run/minissdpd.sock
lease_file=/var/upnp_leases
port=8666
enable_natpmp=yes
enable_upnp=yes
bitrate_up=3500000
bitrate_down=24000000
secure_mode=no
system_uptime=yes
notify_interval=60
clean_ruleset_threshold=20
clean_ruleset_interval=600
allow 1024-65535 $lan_ipaddr/$lan_netmask 1024-65535
deny 0-65535 0.0.0.0/0 0-65535
model_number=1
" > /etc/miniupnpd.conf
###############################################################
cat /etc/miniupnpd.conf.uuid >> /etc/miniupnpd.conf
###############################################################
}

get_param() {
    eval `nvram_buf_get 2860 lan_ipaddr lan_netmask upnpEnabled`
}

stop() {
 $LOG "Stop upnp "
    pid=`pidof miniupnpd`
    count=0
    # try 3 times for correct shutdown
    while kill "$pid" > /dev/null 2>&1; do
	pid=`pidof miniupnpd`
	count="$(($count+1))"
	if [ "$count" = "3" ] || [ "$pid" = "" ]; then
	    break
	fi
	usleep 300000
    done
    # if not correct terminate need kill
    if [ "$pid" != "" ]; then
	kill -SIGKILL "$pid" > /dev/null 2>&1
	if [ -f /var/run/miniupnpd.pid ]; then
	    rm -f /var/run/miniupnpd.pid
	fi
    fi
    ip route del "$upmpm_net" dev "$lan_if" > /dev/null 2>&1
}

case "$1" in
	start)
	    start
	    ;;

	stop)
	    stop
	    ;;

	restart)
	    stop
	    start
	    ;;

	*)
	    echo $"Usage: $0 {start|stop|restart}"
	    exit 1
esac
